//
//  APPersonalEditViewController.m
//  AqualPolo
//
//  Created by dong on 2024/5/8.
//

#import "APPersonalEditViewController.h"
#import "APTextFieldView.h"
#import "APTitleControl.h"
#import "APLoginManager.h"
#import "APDatePickerViewController.h"

@interface APPersonalEditViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) UIImageView *avatarImageView;
@property (nonatomic, strong) APTextFieldView *nickNameView;
@property (nonatomic, strong) APTitleControl *birthdayView;
@property (nonatomic, strong) APTitleControl *countryView;
@property (nonatomic, strong) UIButton *submitButton;

@property (nonatomic, strong) NSDate *birthday;
@property (nonatomic, copy) NSString *country;
@property (nonatomic, strong) NSArray *countrys;
@property (nonatomic, assign) bool isModify;

@end

@implementation APPersonalEditViewController

- (NSArray *)countrys{
    if (!_countrys) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"country" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        NSError *error = nil;
        _countrys = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
        LYLog(@"%@",error);
    }
    return _countrys;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadNaviBar];
    self.naviBar.titleLabel.text = @"Edit Profile";
    [self initUI];
    self.isModify = false;
}

- (void)setIsModify:(bool)isModify{
    _isModify = isModify;
    self.submitButton.alpha = isModify ? 1:0.5;
    self.submitButton.enabled = isModify;
}


- (void)setBirthday:(NSDate *)birthday{
    self.isModify = true;
    _birthday = birthday;
    self.birthdayView.contentLabel.text = [NSDate stringFromDate:self.birthday withFormat:@"yyyy-MM-dd"];
}

- (void)setCountry:(NSString *)country{
    self.isModify = true;
    _country = country;
    self.countryView.contentLabel.text = self.country;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    self.isModify = true;
    return true;
}

- (void)submitButtonDidClick:(UIButton *)sender{
    if (!_isModify) {
        return;
    }
    NSString *nickName = self.nickNameView.textField.text;
    if (nickName.length == 0) {
        return;
    }
    if (!_country) {
        return;
    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setNullObject:nickName forKey:@"nickname"];
    [parameters setNullObject:_country forKey:@"country"];
    [parameters setNullObject:[NSDate stringFromDate:self.birthday withFormat:@"yyyy-MM-dd"] forKey:@"birthday"];
    [self.view ShowProgress];
    [APDataManager postJsonWithUrlString:saveUserInfo timeoutInterval:0 parameters:parameters result:^(NSDictionary * _Nullable res) {
        [self.view removeProgress];
        [self requestUserInfo];
    } failBlock:^(NSString * _Nullable errorMsg) {
        [self.view removeProgress];
        [self.view ShowProgressOnlyLabel:errorMsg];
    }];
   
}

- (void)requestUserInfo{
    APUserModel *userModel = [[APLoginManager shareInstance] userInfo];
    _birthday = [NSDate dateFromString:userModel.birthday];
    _country = userModel.country;
    [self.view ShowProgress];
    NSString *urlString = [NSString stringWithFormat:@"%@?userId=%@",getUserInfo,userModel.userId];
    [APDataManager getDataWithUrlString:urlString result:^(NSDictionary * _Nullable res) {
        [[APLoginManager shareInstance] updateUserInfo:res[@"data"]];
        [self.view ShowProgressOnlyLabel:@"Submit successfully"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:true];
        });
    } failBlock:^(NSString * _Nullable errorMsg) {
        [self.view removeProgress];
        [self.view ShowProgressOnlyLabel:errorMsg];
    }];
}

- (void)birthdayViewDidClick{
    APDatePickerViewController *birthdayVC = [[APDatePickerViewController alloc] init];
    [birthdayVC setCallBack:^(NSDate * _Nullable date) {
        self.birthday = date;
    }];
    [self presentViewController:birthdayVC animated:true completion:nil];
}

- (void)countryControlDidClick{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"countrys" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSString *title in self.countrys) {
        [alertVC addAction:[UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.country = title;
        }]];
    }
    [alertVC addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];

    [self presentViewController:alertVC animated:true completion:nil];
}

- (void)initUI{
    APUserModel *userModel = [[APLoginManager shareInstance] userInfo];
    _avatarImageView = [[UIImageView alloc]init];
    [_avatarImageView sd_setImageWithURL:[NSURL URLWithString:userModel.avatarUrl]];
    _avatarImageView.layer.cornerRadius = 49;
    _avatarImageView.layer.masksToBounds = true;
    [self.view addSubview:_avatarImageView];
    [_avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.naviBar.mas_bottom).offset(68);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(98, 98));
    }];
    
    _nickNameView = [[APTextFieldView alloc] init];
    _nickNameView.textField.delegate = self;
    _nickNameView.titleLabel.text = @"Nick Name";
    _nickNameView.textField.text = userModel.nickname;
    [self.view addSubview:_nickNameView];
    [_nickNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_avatarImageView.mas_bottom).offset(32);
        make.left.equalTo(self.view).offset(32);
        make.right.equalTo(self.view).offset(-32);
        make.height.mas_equalTo(44);
    }];
    
    _birthdayView = [[APTitleControl alloc] init];
    [_birthdayView addTarget:self action:@selector(birthdayViewDidClick) forControlEvents:UIControlEventTouchUpInside];
    _birthdayView.titleLabel.text = @"Date of Birth";
    _birthdayView.contentLabel.text = userModel.birthday;
    _birthday = [NSDate dateFromString:userModel.birthday withFormat:@"yyyy-MM-dd"];
    [self.view addSubview:_birthdayView];
    [_birthdayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nickNameView.mas_bottom).offset(24);
        make.left.equalTo(self.view).offset(32);
        make.right.equalTo(self.view).offset(-32);
        make.height.mas_equalTo(44);
    }];
    
    _countryView = [[APTitleControl alloc] init];
    [_countryView addTarget:self action:@selector(countryControlDidClick) forControlEvents:UIControlEventTouchUpInside];
    _countryView.titleLabel.text = @"Country";
    _countryView.contentLabel.text = userModel.country;
    _country = userModel.country;
    [self.view addSubview:_countryView];
    [_countryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_birthdayView.mas_bottom).offset(24);
        make.left.equalTo(self.view).offset(32);
        make.right.equalTo(self.view).offset(-32);
        make.height.mas_equalTo(44);
    }];
    
    _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _submitButton.alpha = 0.5;
    self.submitButton.enabled = false;
    [_submitButton addTarget:self action:@selector(submitButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [_submitButton setTitle:@"Submit" forState:UIControlStateNormal];
    _submitButton.titleLabel.font = [LYFont fontWithSize:16 fontName:LYFontNamepfm];
    [_submitButton setBackgroundImage:[UIImage imageNamed:@"button_bg"] forState:UIControlStateNormal];
    [self.view addSubview:_submitButton];
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_countryView.mas_bottom).offset(100);
        make.left.equalTo(self.view).offset(32);
        make.right.equalTo(self.view).offset(-32);
        make.height.mas_equalTo(50);
    }];
    
}


@end
